package com.example.project.projectspringcloud.config;

import com.example.project.projectspringcloud.common.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * spring-boot-security 自定义验证码验证
 */
@Component
public class SecurityCustomValidateCode extends OncePerRequestFilter {

    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if(httpServletRequest.getRequestURI().indexOf("/admin/login") > -1 && "post".equals(httpServletRequest.getMethod().toLowerCase())) {
            // 1. 进行验证码的校验
            if(httpServletRequest.getSession().getAttribute(Constants.VALIDATE_CODE) == null || httpServletRequest.getSession().getAttribute(Constants.VALIDATE_CODE) == "") {
                myAuthenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, new AuthenticationException("图片验证码已过期") {
                });
                return ;
            }

            if(httpServletRequest.getParameter("verification").equals(httpServletRequest.getSession().getAttribute(Constants.VALIDATE_CODE))) {
                httpServletRequest.getSession().removeAttribute(Constants.VALIDATE_CODE);
            }
            // 2. 返回错误信息
            else {
                myAuthenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, new AuthenticationException("验证码错误") {
                });
                return ;
            }
        }
        // 3. 校验通过，就放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}

@Component
class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        logger.error("login failure !");
        super.setDefaultFailureUrl("/admin/login?error=true");
        super.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
    }
}